<template>
  <div>
    <el-dialog
      title="机房号源模版导入"
      width="90%"
      top="50px"
      :visible.sync="tfdVisible"
      :before-close="closeTempDlg"
      :destroy-on-close="true"
      class="ky-dialog"
    >
      <div class="tfd-main">
        <div class="appo-header" v-if="tfdVisible">
          <el-form
            :inline="true"
            :model="appoFormData"
            @submit.native.prevent
            class="ky-form-inline ky-form-inline-sm">
            <el-form-item label="机房">
              <roomCascader :room.sync="appoFormData.room" @roomChange="roomChange"></roomCascader>
            </el-form-item>
            <!-- <el-form-item class="item-line-36">
              <el-radio-group v-model="appoFormData.status" style="margin-top: 0;" @change="statusChange">
                <el-radio-button label="day">日模板</el-radio-button>
                <el-radio-button label="week">周模板</el-radio-button>
              </el-radio-group>
            </el-form-item> -->
          </el-form>
          <div style="float: right;">
            <el-button size="small" type="primary" @click="saveImport">导入</el-button>
          </div>
        </div>
        <div class="appo-main" v-show="checkRomeArr.length>0">
          <fullschedule
            v-loading="loading"
            ref="fullschedule"
            :sidebardata="sidebardata"
            :is-edit="true"
            :is-add="false"
            :appo-repair="appoRepair"
            :all-ckb="allCheckbox"
            :status-filter="statusFilter"
            status-template="template"
            :checkbox-show="true"
            :row-height="84"
            @handleAppoInfo="handleAppoInfo"
          ></fullschedule>
        </div>
        <roomNone v-show="checkRomeArr.length===0"></roomNone>
      </div>
      <!-- <div slot="footer" class="efd-footer">
        <span style="margin-right: 20px;color: #f00;" v-show="appoFormData.status === 'week'">提示：周模板导入，会覆盖周模板所有时段号源！</span>
        <el-button size="small" @click="closeTempDlg">取消</el-button>
        <el-button size="small" type="primary" @click="saveImport">导入</el-button>
      </div> -->
    </el-dialog>
    <!-- 查看预约信息详情 -->
    <!-- <appoReleaseInfo
      ref="appoReleaseInfo"
    ></appoReleaseInfo> -->
  </div>
</template>

<script>

import { getHospitalSetting } from '@/api/api'
import { setSidebarDataTemp } from '@/utils/utils'
import {
  getAppointmentTempList,
  getAppTempAppointmentlistRoom
} from '@/api/room'
import fullschedule from '../components/fullschedule'
// import week from '../components/week'
// import appoReleaseInfo from '../components/appoReleaseInfo'
import roomCascader from '../components/roomCascaderBase'
import { dateFormatter } from '@/utils/validate'
import { getWeekStartEndDate, seasonCalCurrDate, flattenDeep } from '@/utils/schedule'
import roomNone from '@/components/roomNone'
export default {
  components: { roomCascader, fullschedule, roomNone },
  props: {
    allCheckbox: {
      type: Boolean,
      default: false
    },
    appoRepair: {
      type: Boolean,
      default: false
    },
    templateType: {
      type: String,
      default: 'template' // schedule
    }
  },
  data() {
    return {
      loading: false,
      appointmentData: [],
      curDate: dateFormatter(new Date()),
      checkRomeArr: [], // 查询数据机房联级数组
      // 机房，查询条件数据
      checkRoomObj: {
        HospitalCode: '',
        StartDate: '',
        EndDate: '',
        DepArea: '',
        Dep: '',
        ModalityType: '',
        CheckRoom: '',
        AppointmentStatus: '', // 预约时段状态:暂停预约、节假日、正常预约、设备故障、计划排班；单选
        IsHasFilters: true
      },
      tfdVisible: false,
      // 排班条件
      appoFormData: {
        room: [],
        month: '',
        week: '',
        day: '',
        type: false,
        status: 'day' // week: 周，day: 日
      },
      weekDateFull: [],
      // 排班
      fullscheduleIsEdit: false,
      sidebardata: [],
      statusFilter: '暂停预约、节假日、正常预约、设备故障、计划排班'
    }
  },
  created() {
    console.log('created=>templateFullscheduleDialog')
  },
  beforeDestroy() {
    console.log('beforeDestroy=>templateFullscheduleDialog')
  },
  methods: {
    async init(data, iDate) {
      this.curDate = dateFormatter(new Date(iDate), false)
      this.tfdVisible = true
    },
    // 机房改变
    async roomChange(roomData) {
      if (roomData && roomData.length > 0) {
        console.log('机房改变====', roomData)
        this.checkRomeArr = [...roomData]
        this.checkRoomObj.HospitalCode = roomData[0]
        this.checkRoomObj.DepArea = roomData[1]
        this.checkRoomObj.Dep = roomData[2]
        this.checkRoomObj.ModalityType = roomData[3]
        this.checkRoomObj.CheckRoom = roomData[4]
        this.checkRoomObj.AppointmentStatus = ''
        await this.getWeekDateTimeFull()
        await this.getAppoTimeTemp()
        this.$nextTick(() => {
          this.$refs.fullschedule.init({ date: this.curDate, sidebardata: this.sidebardata })
        })
        this.getAppoTempList()
      } else {
        this.checkRomeArr = []
        this.checkRoomObj.HospitalCode = ''
        this.checkRoomObj.DepArea = ''
        this.checkRoomObj.Dep = ''
        this.checkRoomObj.ModalityType = ''
        this.checkRoomObj.CheckRoom = ''
        this.weekDateFull = []
      }
    },
    // 导入
    saveImport() {
      // 获取排班组件内的 排班模板数据
      let schedule = JSON.parse(JSON.stringify(this.$refs.fullschedule.scheduledata))
      console.log('saveImport=>schedule', JSON.stringify(schedule))
      let scheduledata = []
      console.log('this.appoFormData', this.appoFormData)
      let isHaveChecked = false // 判断号源是否有勾选
      schedule.forEach((itemSchedule, indexSchedule) => {
        scheduledata.push(itemSchedule)
        itemSchedule.appointment.forEach((itemAppoArr, indexAppoArr) => {
          itemAppoArr.forEach(item => {
            if (item.isChecked) {
              isHaveChecked = true
            }
          })
        })
      })
      console.log('scheduledata', scheduledata)
      if (isHaveChecked) { // 若有勾选则只导入勾选的号源
        scheduledata.forEach((itemSchedule, indexSchedule) => {
          console.log('scheduledata[indexSchedule].appointment', scheduledata[indexSchedule].appointment)
          // scheduledata[indexSchedule].appointment = [[], []]
          itemSchedule.appointment.forEach((itemAppoArr, indexAppoArr) => {
            console.log('itemAppoArr', itemAppoArr)
            console.log('filterResult', itemAppoArr.filter(itemAppo => itemAppo.isChecked))
            scheduledata[indexSchedule].appointment[indexAppoArr] = itemAppoArr.filter(itemAppo => itemAppo.isChecked)
          })
        })
      }
      // 获取排班组件内的 排班模板数据
      // const schedule = JSON.parse(JSON.stringify(this.$refs.fullschedule.scheduledata))
      // let scheduledata = []
      // // 判断导入的状态，周、日
      // if (this.appoFormData.status === 'day') {
      //   schedule.forEach(item => {
      //     if (item.checkedAll) {
      //       scheduledata.push(item)
      //     }
      //   })
      //   if (scheduledata.length === 0) {
      //     this.$message.warning('请选中要导入的号源模板日期！')
      //     return
      //   }
      // } else {
      //   scheduledata = JSON.parse(JSON.stringify(schedule))
      // }
      console.log('scheduledata', scheduledata)
      console.log('scheduledata.length', scheduledata.length)
      let scheduledataResult = []
      let appoArr = []
      scheduledata.forEach((itemSchedule, indexSchedule) => {
        appoArr = flattenDeep(itemSchedule.appointment)
        if (appoArr.length) {
          scheduledataResult.push(itemSchedule)
        }
      })
      if (scheduledataResult.length > 0) {
        this.$emit('importDataContrast', { importScheduleData: scheduledataResult, isWeek: this.appoFormData.status === 'week', isTemp: true })
      }
      // console.log('scheduledata', scheduledata)
    },
    // 查看、编辑预约排班信息
    handleAppoInfo(data) {
      // console.log(data)
      // this.$refs.appoReleaseInfo.init(data.appoInfo)
    },
    // 查询，获取排班模板数据
    async getAppoTempList() {
      this.loading = true
      const appodata = this.templateType === 'template'
        ? await getAppointmentTempList(this.checkRoomObj)
        : await getAppTempAppointmentlistRoom(this.checkRoomObj)

      this.loading = false
      console.log('查询，获取排班模板数据 getAppoTempList', JSON.parse(JSON.stringify(appodata)))
      this.$refs.fullschedule.appoPull(appodata, null, null, true)
    },
    // 获取时段数据,计算时段
    getAppoTimeTemp() {
      return new Promise(async resolve => {
        const depArr = (this.checkRoomObj.Dep && this.checkRoomObj.Dep.indexOf('-') > -1 && this.checkRoomObj.Dep.split('-')) || ''
        let dep = (depArr && depArr.length && depArr[depArr.length - 1]) || ''
        if (this.checkRoomObj.Dep && this.checkRoomObj.Dep.indexOf('-') == -1) {
          dep = this.checkRoomObj.Dep
        }
        const param = {
          HospitalCode: this.checkRoomObj.HospitalCode,
          depArea: this.checkRoomObj.DepArea,
          dep
        }
        await getHospitalSetting(param).then(async res => {
          if (res && res.code === 10000) {
            const season = await seasonCalCurrDate(res.content.seasonSettings, this.weekDateFull[0], true, false, true)
            this.sidebardata = season.sidebardata
            setSidebarDataTemp(JSON.stringify(season.sidebardata))
          }
        })
        resolve()
      })
    },
    // 获取排班一周的完整时间数组
    getWeekDateTimeFull() {
      return new Promise(async resolve => {
        this.weekDateFull = await getWeekStartEndDate(this.curDate)
        if (this.weekDateFull.length > 0) {
          this.checkRoomObj.SelectDate = this.weekDateFull[0]
          this.checkRoomObj.StartDate = this.weekDateFull[0]
          this.checkRoomObj.EndDate = this.weekDateFull[this.weekDateFull.length - 1]
        }
        resolve()
      })
    },
    // 导入模式变化
    statusChange(val) {
      // console.log(val)
      this.fullscheduleIsEdit = val === 'day'
    },
    // 关闭
    closeTempDlg() {
      this.tfdVisible = false
      this.$emit('closeTempDlg')
    }
  }
}
</script>

<style lang="scss" scoped>
.tfd-main{
  padding: 0 15px;
  min-height: 500px;
}
.appo-header{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item-line-36 /deep/ .el-form-item__content{
  line-height: 36px;
}
</style>
